<template>
	<view class="detailsBox">
		<view class="productInfoBox">
			<view class="leftInfo">
				<view class="imgbox">
					<!-- <my-Image class="img" :src="details.commodityPic" mode="aspectFill"/> -->
					<image class="img" :src="details.commodityPic || '/static/imgs/default.png'" mode="aspectFill"></image>
				</view>
				<!-- <text class="integral">{{details.unitPrice}}元</text> -->
			</view>
			<view class="info">
				<view class="title">{{details.commodityName}}</view>
				<view class="rp">购买数量</view>
				<view class="number">
					<number-selector v-model="quantity"/>
				</view>
				<view class="price">价格：<text class="num">{{details.unitPrice}}元</text></view>
			</view>
		</view>
		<view class="detailsCon">
			<view class="title">商品详情</view>
			<view class="content" v-html="details.commodityDetail">
				
			</view>
		</view>
		<view class="bottomBtn">
			<view class="info">
				支付:{{details.unitPrice * quantity}}元
				<!-- <text class="buz">余额不足，还差120积分</text> -->
			</view>
			<view class="btn" @click="openPayType">支付</view>
		</view>
	</view>
</template>

<script>
	import {mapGetters} from "vuex"
	import {getMallDetails} from '@/api/index.js'
	import numberSelector from '@/components/numberSelector/numberSelector.vue'
	import {integralPay} from '@/api/index.js'
	import user from "@/common/user.js"
	export default {
		components:{
			numberSelector
		},
		data() {
			return {
				id:'',
				quantity:1
			}
		},
		computed:{
		    ...mapGetters({
		        details:'base/details',
				buyInfo:'base/buyInfo'
		    })
		},
		async onLoad(options){
			if(options && options.id){
				this.id = options.id
				console.log('this.id:',this.id)
			}
			const res = await getMallDetails({id:this.id})
			this.$store.commit('base/set_details',res)
		},
		created() {
			
			//console.log("details:",this.details)
			this.$store.commit('base/set_init_buyInfo')
			console.log("buyInfo:",this.buyInfo)
		},
		methods: {
			openPayType(){
				//#ifdef H5
				uni.showModal({
					title: '提示',
					content:'请下载app支付',
					success(ret) {
						if (ret.confirm) {
							uni.navigateTo({
								url: '/pages/login/download'
							})
						}
					}
				})
				//#endif
				
				//#ifndef H5
				let itemList = []
				if(this.details.allowPayMethod.indexOf('alipay_app')>-1){
					itemList.push('支付宝')
				}
				if(this.details.allowPayMethod.indexOf('wechatpay_app_pay')>-1){
					itemList.push('微信')
				}
				
				if(itemList.length == 1){
					if(itemList[0] == '支付宝'){
						this.aliPay()
					}else if(itemList[0] == '微信'){
						this.wechatPay()
					}
				}else if(itemList.length > 1){
					uni.showActionSheet({
						itemList,
						success:  (res) =>{
							if(res.tapIndex==0){
								this.aliPay()
							}else if(res.tapIndex==1){
								this.wechatPay()
							}
						},
						fail: function (res) {
							console.log(res.errMsg);
						}
					});
				}
				
				//#endif
			},
			async aliPay(){
				const res = await integralPay({
					dispatchMethod: 2,
					mallCommodityId:parseInt(this.id), //11,
					payMethod: "alipay_app",
					purchaseCount: this.quantity,
					userId: user.getUserId()
				})
				if(res.payBody){
					//this.showModal('兑换成功','/pages/integral/mall/mall')
					//订单对象，从服务器获取
					const orderInfo = this.escape2Html(res.payBody)
					//console.log("orderInfo:",orderInfo)
					uni.requestPayment({
					    provider: 'alipay',
					    orderInfo,
					    success:  (ret)=> {
					        //console.log('success:' + JSON.stringify(res));
							this.showModal('支付成功','/pages/index/my')
					    },
					    fail: (err)=> {
					        //console.log('fail:' + JSON.stringify(err));
							const errMsg = JSON.stringify(err)
							if(errMsg.indexOf('取消支付')>-1){
								uni.showToast({
									title: '取消支付',
									icon:'none'
								});
							}else{
								this.showModal(errMsg)
							}
					    }
					});
				}else{
					this.showModal(res.errorMessage)
				}
			},
			async wechatPay(){

				const res = await integralPay({
					dispatchMethod: 2,
					mallCommodityId:parseInt(this.id),
					payMethod: "wechatpay_app_pay",
					purchaseCount: this.quantity,
					userId: user.getUserId()
				})

				if(res.orderNo){
					//this.showModal('兑换成功','/pages/integral/mall/mall')
					uni.requestPayment({
					    "provider": "wxpay", 
					    "orderInfo": {
					        "appid": res.payBody.appid,  // 微信开放平台 - 应用 - AppId，注意和微信小程序、公众号 AppId 可能不一致
					        "noncestr": res.payBody.nonceStr, // 随机字符串
					        "package": res.payBody.packageVal,        // 固定值
					        "partnerid": res.payBody.partnerId,      // 微信支付商户号
					        "prepayid": res.payBody.prepayId, // 统一下单订单号 
					        "timestamp": res.payBody.timestamp,        // 时间戳（单位：秒）
					        "sign": res.payBody.sign // 签名，这里用的 MD5/RSA 签名
					    },
					    success:ret=> {
							//this.showModal(JSON.stringify(ret))
							this.showModal('支付成功','/pages/index/my')
						},
					    fail:err=> {
							this.showModal(JSON.stringify(err))
						}
					})
				}else{
					this.showModal(res.errorMessage)
				}
			},
			showModal(content,url){
				uni.showModal({
					title: '提示',
					content,
					showCancel:false,
					success(ret) {
						if (ret.confirm && url) {
							uni.switchTab({url})
						}
					}
				})
			},
			//转意符换成普通字符  
			escape2Html(str) {  
			    var arrEntities = {  
			        'lt': '<',  
			        'gt': '>',  
			        'nbsp': ' ',  
			        'amp': '&',  
			        'quot': '"'  
			    };  
			    return str.replace(/&(lt|gt|nbsp|amp|quot);/ig, function(all, t) {  
			        return arrEntities[t];  
			    });  
			}
		}
	}
</script>

<style lang="scss" scoped>
	.detailsBox{
		box-sizing: border-box;
		padding: 20rpx;
		font-size: 28rpx;
		
		.detailsCon{
			box-sizing: border-box;
			margin: 20rpx 0 0 0;
			width: 100%;
			border-radius: 20rpx;
			background: #fff;
			overflow: hidden;
			padding: 20rpx;
			.title{
				font-weight: bold;
				font-size: 34rpx;
				text-align: center;
				padding: 20rpx 0 40rpx 0;
			}
			.content{
				line-height: 50rpx;
				font-size: 28rpx;
			}
		}
		.bottomBtn{
			display: flex;
			box-sizing: border-box;
			position: fixed;
			z-index: 900;
			left: 0;
			bottom: 0;
			width: 100%;
			height: 110rpx;
			background-color: #fff;
			box-shadow: 0 0 10rpx #ddd;
			padding: 0 20rpx;
			.info{
				display: flex;
				flex-flow: column;
				justify-content: center;
				flex: 1;
				font-weight: bold;
				font-size: 30rpx;
				.buz{
					display: block;
					color: #ca0000;
					font-size: 26rpx;
					padding: 10rpx 0 0 0;
				}
			}
			.btn{
				width: 200rpx;
				height: 80rpx;
				line-height: 80rpx;
				background-color: #238de8;
				border-radius: 40rpx;
				text-align: center;
				font-size: 32rpx;
				color: #fff;
				margin: 15rpx 0 0 0;
			}
		}
	}
	.productInfoBox{
		box-sizing: border-box;
		display: flex;
		width: 100%;
		border-radius: 20rpx;
		background: #fff;
		overflow: hidden;
		padding: 20rpx;
		.leftInfo{
			width: 260rpx;
			.imgbox{
				width: 100%;
				height: 220rpx;
				overflow: hidden;
				.img{
					display: block;
					width: 100%;
					height: 100%;
				}
			}
			.integral{
				display: block;
				text-align: center;
				color:#238de8;
				font-size: 26rpx;
				padding: 15rpx 0;
			}
		}
		.info{
			flex: 1;
			padding: 0 0 0 20rpx;
			font-size: 28rpx;
			line-height: normal;
			.title{
				display: block;
				font-size: 28rpx;
				font-weight: bold;
			}
			.rp{
				padding: 15rpx 0;
			}
			.number{
				width: 300rpx;
			}
			.price{
				padding: 20rpx 0 0 0;
				.num{
					color: #ca0000;
					font-weight: bold;
				}
			}
		}
	}
</style>
<style>
	.uni-actionsheet{
		z-index: 1000;
	}
</style>
